package com.xhc.demo.controller;

import com.xhc.demo.dto.AdminLoginRequest;
import com.xhc.demo.dto.OrderDTO;
import com.xhc.demo.dto.SearchOrdersRequest;
import com.xhc.demo.entity.AdminUser;
import com.xhc.demo.entity.Order;
import com.xhc.demo.entity.Photo;
import com.xhc.demo.service.AdminService;
import com.xhc.demo.repository.OrderRepository;
import com.xhc.demo.repository.PhotoRepository;
import com.xhc.demo.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = {"http://localhost:8080", "http://192.168.31.127:8080" , "http://p.mrxxhc.cn/" , "https://p.mrxxhc.cn/"}, allowCredentials = "true")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PhotoRepository photoRepository;

    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(@RequestBody AdminLoginRequest request) {
        logger.info("admin params -> " + request.toString());
        AdminUser adminUser = adminService.login(request.getUsername(), request.getPassword());
         
        if (adminUser != null && adminUser.getToken() != null) {
            Map<String, Object> data = new HashMap<>();
            data.put("token", adminUser.getToken());
            data.put("username", adminUser.getUsername());
            data.put("role", adminUser.getRole());
            logger.info("admin result -> " + data.toString());
            return Utils.getResponseJson(data);
        } else {
            return Utils.getErrorJson(401, "用户名或密码错误");
        }
    }

    @PostMapping(value = "/search_orders", produces = MediaType.APPLICATION_JSON_VALUE)
    public String searchOrders(@RequestBody SearchOrdersRequest request) {
        logger.info("search_orders params -> " + request.toString());
        
        // 验证token
        AdminUser adminUser = adminService.validateToken(request.getToken());
        if (adminUser == null) {
            return Utils.getErrorJson(401, "未登录或登录已过期");
        }

        try {
            // 创建分页请求
            PageRequest pageRequest = PageRequest.of(request.getPage(), request.getSize());
            
            // 查询订单
            Page<Order> ordersPage = orderRepository.searchOrders(
                // request.getPaymentTime(),
                pageRequest
            );

            // 转换为DTO
            List<OrderDTO> orderDTOs = ordersPage.getContent().stream()
                .map(OrderDTO::fromEntity)
                .collect(Collectors.toList());

            // 创建DTO的Page对象
            Page<OrderDTO> dtoPage = new PageImpl<>(
                orderDTOs, 
                pageRequest, 
                ordersPage.getTotalElements()
            );
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("content", dtoPage.getContent());
            data.put("totalElements", dtoPage.getTotalElements());
            data.put("totalPages", dtoPage.getTotalPages());
            data.put("currentPage", dtoPage.getNumber());
            data.put("size", dtoPage.getSize());
            String responce = Utils.getResponseJson(data);
             
            return responce;
        } catch (Exception e) {
            logger.error("Search orders error", e);
            return Utils.getErrorJson(500, "查询订单失败：" + e.getMessage());
        }
    }

    @PostMapping("/download-photos")
    public ResponseEntity<?> downloadPhotos(@RequestBody Map<String, Object> request) {
        String token = (String) request.get("token");
        Long orderId = Long.parseLong(request.get("orderId").toString());

        // 验证管理员token
        AdminUser adminUser = adminService.validateToken(token);
        if (adminUser == null) {
            return ResponseEntity.ok(Utils.getErrorJson(401, "未登录或登录已过期"));
        }

        // 获取订单及其照片
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            return ResponseEntity.ok(Utils.getErrorJson(404, "订单不存在"));
        }

        if (order.getPhotos() == null || order.getPhotos().isEmpty()) {
            return ResponseEntity.ok(Utils.getErrorJson(404, "该订单没有照片"));
        }

        // 返回照片URL列表
        List<Map<String, String>> photoUrls = order.getPhotos().stream()
            .map(photo -> {
                Map<String, String> urls = new HashMap<>();
                urls.put("imageUrl", Utils.getQiniuPrivateDownloadUrl(photo.getImageUrl()));
                urls.put("fileName", photo.getPhotoId() + "_" + photo.getMaterial() + "_" + photo.getSize() + ".jpg");
                return urls;
            })
            .collect(Collectors.toList());

        return ResponseEntity.ok(Utils.getResponseJson(photoUrls));
    }

    @PostMapping(value = "/modify_order_number", produces = MediaType.APPLICATION_JSON_VALUE)
    public String modifyOrderNumber(@RequestBody Map<String, String> request) {
        logger.info("modify_order_number params -> " + request.toString());
        
        // 验证token
        AdminUser adminUser = adminService.validateToken(request.get("token"));
        if (adminUser == null) {
            return Utils.getErrorJson(401, "未登录或登录已过期");
        }

        try {
            // 获取参数
            String orderId = request.get("orderId");
            String newOrderNumber = request.get("orderNumber");

            // 检查参数是否为空
            if (orderId == null || newOrderNumber == null) {
                return Utils.getErrorJson(400, "订单ID或新订单号不能为空");
            }

            // 查找订单
            Order order = orderRepository.findById(Long.parseLong(orderId)).orElse(null);
            if (order == null) {
                return Utils.getErrorJson(404, "未找到指定订单");
            }

            // 修改订单号
            order.setOrderNumber(newOrderNumber);
            orderRepository.save(order);

            // 返回成功响应
            Map<String, Object> data = new HashMap<>();
            data.put("message", "订单号修改成功");
            data.put("orderId", orderId);
            data.put("newOrderNumber", newOrderNumber);
            
            return Utils.getResponseJson(data);
        } catch (Exception e) {
            logger.error("Modify order number error", e);
            return Utils.getErrorJson(500, "修改订单号失败：" + e.getMessage());
        }
    }

    @PostMapping(value = "/check_nfc", produces = MediaType.APPLICATION_JSON_VALUE)
    public String checkNfc(@RequestBody Map<String, String> request) {
        logger.info("check_nfc params -> " + request.toString());
        
        // 验证token
        AdminUser adminUser = adminService.validateToken(request.get("token"));
        if (adminUser == null) {
            return Utils.getErrorJson(401, "未登录或登录已过期");
        }

        try {
            // 获取参数
            String userIdStr = request.get("userId");
            String photoIdStr = request.get("photoId");

            // 检查参数是否为空
            if (userIdStr == null || photoIdStr == null) {
                return Utils.getErrorJson(400, "用户ID或照片ID不能为空");
            }

            // 转换为Long类型
            Long userId = Long.parseLong(userIdStr);
            Long photoId = Long.parseLong(photoIdStr);

            // 查找照片
            Photo photo = photoRepository.findById(photoId).orElse(null);

            if (photo == null) {
                return Utils.getErrorJson(404, "未找到照片");
            }

            if(photo.getUser() == null || photo.getUser().getUserId() != userId) {
                return Utils.getErrorJson(403, "照片不属于指定用户");
            }
     

            // 返回成功响应
            Map<String, Object> data = new HashMap<>();
            data.put("photoUrl", Utils.getQiniuPrivateDownloadUrlThumbil(photo.getImageUrl()));
            data.put("photoId", photoIdStr);
            data.put("userId", userIdStr);
            
            return Utils.getResponseJson(data);
        } catch (Exception e) {
            logger.error("Check NFC error", e);
            return Utils.getErrorJson(500, "查询照片失败：" + e.getMessage());
        }
    }
}
